package com.xquant.databasemanagement.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.xquant.databasemanagement.bean.DataBaseObject;
import com.xquant.databasemanagement.bean.DatabaseBean;
import com.xquant.databasemanagement.config.Config;

import java.io.*;


public class XMLService {

    ObjectMapper mapper = new XmlMapper();

    public void saveXMLFile(DatabaseBean databaseModel,String fileUrl,String fileName) throws IOException {
        OutputStream out = null;
        try {
            databaseModel.setDatabaseName(fileName);
            out = new FileOutputStream(new File(fileUrl, fileName));
            mapper.writerWithDefaultPrettyPrinter().writeValue(out, databaseModel);
            mapper.writerWithDefaultPrettyPrinter().writeValueAsString(databaseModel);
        }finally {
            if (out!=null){
                out.close();
            }
        }


    }


    public DatabaseBean openXMLFile(String fileURL, String fileName) throws IOException {
        InputStream in = null;
        try {
            in = new FileInputStream(new File(fileURL,fileName));
            return mapper.readValue(in, DatabaseBean.class);
        }finally {
            if(in != null){
                in.close();
            }
        }
    }



    public String createXML(DataBaseObject dataBaseBean) throws JsonProcessingException {
        return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(dataBaseBean);

    }


    private XMLService(){}

    public static XMLService getXmlService() {
        return xmlService;
    }

    private static XMLService xmlService = new XMLService();



}
